/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **************************************************************************
 * MIFSS  - content storage system
 *
 *
 * @uthors: uros.kristan@gmail.com (Uroš Kristan ) Urosk.NET
 *         jernej.svigelj@gmail.com (Jernej Švigelj)
 */
package net.monare.mifss.workers;

import net.monare.mifss.configurations.pojo.ContentMetaDataDef;
import net.monare.mifss.configurations.pojo.ContentMetaDataSequence;
import net.monare.mifss.configurations.pojo.StorageDef;
import net.monare.mifss.exceptions.ContentMetaDataDaoException;
import net.monare.mifss.lib.db.DataResult;
import net.monare.mifss.workers.interfaces.ContentMetaDataDao;
import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;


@Repository()
@Scope("prototype")
public class ContentMetaDataDaoImpl implements ContentMetaDataDao {

    protected static Logger logger = Logger.getLogger(ContentMetaDataDaoImpl.class);
    @PersistenceContext
    EntityManager em;

    @Transactional
    public void removeContentMetaData(String contentUuid, StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            String query = "select c from ContentMetaDataDef c where c.contentMetaDataKey.uuid = :uuid and c.contentMetaDataKey.storageName = :storageName";
            Query q = em.createQuery(query);

            q.setParameter("uuid", contentUuid);
            q.setParameter("storageName", storageDef.getName());

            List<ContentMetaDataDef> contentMetaDataDefList = q.getResultList();

            if (contentMetaDataDefList.size() > 1) {
                throw new ContentMetaDataDaoException("Inconsistency on content detected. More than one ContentMetaDataDef objects found in one storage.");
            } else {
                // remove selected
                em.remove(contentMetaDataDefList.get(0));
            }


        } catch (Exception e) {

            String errMessage = "Error occurred while trying to delete ContentMetaDefinition with id " + contentUuid + " for reason: "
                    + e.getMessage();
            logger.error(errMessage, e);
            throw new ContentMetaDataDaoException(errMessage, e);

        }

    }

    @Transactional
    public void removeAllContentMetaData(StorageDef storageDef) throws ContentMetaDataDaoException {

        // TODO : implement with drop table partition

        try {

            Query q = em.createQuery("DELETE FROM ContentMetaDataDef c WHERE c.contentMetaDataKey.storageName = :storageName");

            q.setParameter("storageName", storageDef.getName());
            q.executeUpdate();

        } catch (Exception e) {

            String errMessage = "Error occurred while trying to remove content meta data for storage " + storageDef + " . Reason for failure: " + e.getMessage();
            logger.error(errMessage, e);
            throw new ContentMetaDataDaoException(errMessage, e);

        }

    }


    @Transactional
    public DataResult findAll(StorageDef storageDef, int start, int offset) throws ContentMetaDataDaoException {

        try {

            String query = "SELECT c from ContentMetaDataDef c WHERE c.contentMetaDataKey.storageName = :storageName";
            Query q = em.createQuery(query);

            q.setParameter("storageName", storageDef.getName());
            q.setFirstResult(start);
            q.setMaxResults(offset);

            List<ContentMetaDataDef> contentMetaDataDefList = q.getResultList();

            DataResult dataResult = new DataResult();

            dataResult.setList(contentMetaDataDefList);
            dataResult.setCount(contentMetaDataDefList.size());
            dataResult.setFrom(start);
            dataResult.setLimit(offset);

            return dataResult;

        } catch (DataAccessException e) {

            String errMessage = "Error occurred while trying to get content meta data for storage: " + storageDef
                    + ". Cause for error: " + e.getMessage();
            logger.error(errMessage, e);
            throw new ContentMetaDataDaoException(errMessage, e);

        }
    }

    public ContentMetaDataDef getContentMetaDefFromUUID(String contentUuid, StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            String query = "select c from ContentMetaDataDef c where c.contentMetaDataKey.uuid = :uuid and c.contentMetaDataKey.storageName = :storageName";
            Query q = em.createQuery(query);

            q.setParameter("uuid", contentUuid);
            q.setParameter("storageName", storageDef.getName());

            List<ContentMetaDataDef> contentMetaDataDefList = q.getResultList();

            if (contentMetaDataDefList.size() > 1) {
                throw new ContentMetaDataDaoException("Inconsistency on content detected. More than one ContentMetaDataDef objects found in one storage.");
            } else if (contentMetaDataDefList.size() == 1) {
                return contentMetaDataDefList.get(0);
            } else {
                // No ContentMetaData objects found
                return null;
            }

        } catch (DataAccessException e) {

            String errMessage = "Error occurred while trying to get content with UUID " + contentUuid + " for storage "
                    + storageDef + ". " + e.getMessage();
            logger.error(errMessage, e);
            throw new ContentMetaDataDaoException(errMessage, e);

        }

    }



    @PostConstruct
    public void init() {
        logger.info("Initializing mifss Saver engine");
    }


    public Long getMaxId(StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            String query = "select s from ContentMetaDataSequence s where s.storageName = :storageName";
            Query q = em.createQuery(query);
            q.setParameter("storageName", storageDef.getName());

            ContentMetaDataSequence dataSequence = (ContentMetaDataSequence) q.getSingleResult();

            return dataSequence.getSequenceValue();

        } catch (Exception x){

            String errMessage = "Error occurred while trying to retrieve max id for storage " + storageDef + ". " + x.getMessage();
            logger.error(errMessage, x);
            throw new ContentMetaDataDaoException(errMessage, x);

        }

    }

    @Transactional
    public void createMaxId(StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            ContentMetaDataSequence dataSequence = new ContentMetaDataSequence();
            dataSequence.setStorageName(storageDef.getName());
            dataSequence.setSequenceValue(0l);
            em.persist(dataSequence);

        } catch (Exception x) {
            String errMessage = "Error occurred while trying to set max id for storage " + storageDef + ". " + x.getMessage();
            logger.error(errMessage, x);
            throw new ContentMetaDataDaoException(errMessage, x);
        }
    }

    @Transactional
    public void setMaxId(StorageDef storageDef, Long id) throws ContentMetaDataDaoException {

        try {

            String query = "update ContentMetaDataSequence set sequenceValue = :id where storageName = :storageName";
            Query q = em.createQuery(query);

            q.setParameter("storageName", storageDef.getName());
            q.setParameter("id", id);

            q.executeUpdate();

        } catch (Exception x) {
            String errMessage = "Error occurred while trying to set max id for storage " + storageDef + ". " + x.getMessage();
            logger.error(errMessage, x);
            throw new ContentMetaDataDaoException(errMessage, x);
        }
    }

    @Transactional
    public void removeMaxId(StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            String query = "select s from ContentMetaDataSequence s where s.storageName = :storageName";
            Query q = em.createQuery(query);
            q.setParameter("storageName", storageDef.getName());

            ContentMetaDataSequence dataSequence = (ContentMetaDataSequence) q.getSingleResult();
            em.remove(dataSequence);
            em.flush();

        } catch (Exception x){

            String errMessage = "Error occurred while trying to remove max id for storage " + storageDef + ". " + x.getMessage();
            logger.error(errMessage, x);
            throw new ContentMetaDataDaoException(errMessage, x);


        }
    }

    @Transactional
    public ContentMetaDataDef insertContentMetaDataDef(ContentMetaDataDef cm, StorageDef storageDef) throws ContentMetaDataDaoException {

        try {

            Long nextId = getMaxId(storageDef) + 1;

            // set next id
            cm.setIdContent(nextId);
            cm.setStorageName(storageDef.getName());

            // persist ContentMetaDataDef object
            em.persist(cm);

            // store max id
            setMaxId(storageDef, nextId);

            return cm;


        } catch (Exception e) {

            String errMessage = "Error occurred while trying to insert content meta data  for storage : " + storageDef + ". " + e.getMessage();
            logger.error(errMessage, e);
            throw new ContentMetaDataDaoException(errMessage, e);

        }

    }


}